import { base16Encode } from "./base16";
import { fetchAskData } from "./tools";
import { isPC } from "../env/browserInfo";
import { navPagePrefix } from "../env/config";
export class UserProfile {
    appName: string;
    logined: boolean = false;
    userName: string = "";
    userId: string = "";
    userRights: string = "";
    password: string = "";
    homePage: string = "";
    msg: string = "";
    acceptWebp: boolean = true;
    defaultVoucherType: string = "";
    dataUrlPrefix?: string;
    userType: string = "";
    constructor(appName: string) {
        this.appName = appName;
        this.init();
    }
    init() {
        this.logined = false;
        this.userName = "";
        this.userId = "";
        this.password = "";
        this.homePage = "/";
        this.msg = "";
        this.userRights = "";
        this.defaultVoucherType = "02";
        this.acceptWebp = isPC;
        this.dataUrlPrefix = "";
    }
    userRightCheck(operRight: string = ""): boolean {
        return operRight ? this.userRights.indexOf(operRight) >= 0 : true;
    }
    parseJson(json: string, forLogin: boolean = false): boolean {
        let self = this;
        let result = false;
        if (json) {
            try {
                let profile: any = JSON.parse(json);
                if (forLogin) {
                    function row2User(data: any): any {
                        //console.log(JSON.stringify(data));
                        self.msg = data.msg;
                        let result: any = {};
                        if (data.msg === "ok")
                            data = data.data;
                        if (data.rowCount) {
                            result = { ...data.rowsObj[0], logined: true };
                        } else {
                            self.msg = "提供的资料无法通过系统认证,请重新输入！";
                            result = {
                                logined: false,
                                userId: "",
                                userName: ""
                            };
                        }
                        return result;
                    }
                    profile = row2User(profile);
                }
                let keys = Object.keys(profile);
                for (let k of keys) {
                    (this as any)[k] = profile[k];
                }
                if (this.logined) {
                    if (this.userType === "员工") {
                        this.homePage = navPagePrefix + "ledger";
                    } else if (this.userRights.indexOf("F") >= 0) {
                        this.homePage = navPagePrefix + "examer";
                    } else {
                        this.homePage = navPagePrefix + "workloadoper";
                    }
                } else {
                    this.homePage = "/";
                }
            } catch (error) {
                this.msg = "解析登录数据失败，可能是无法连接服务器";
                this.logined = false;
            }
            result = this.logined;
        }
        return result;
    }
    localStorageId(): string {
        return this.appName + '.' + this.userId + ".userProfile";
    }
    load(): boolean {
        const json = localStorage.getItem(this.localStorageId()) || "";
        return this.parseJson(json, false);
    }
    save(): boolean {
        const { defaultVoucherType, acceptWebp } = this;
        let json = JSON.stringify({ defaultVoucherType, acceptWebp });
        console.log("userProfile save as: " + json);
        localStorage.setItem(this.localStorageId(), json);
        return true;
    }
    async fetchConfig() {
        try {
            const rand = new Date().toLocaleTimeString();
            const response = await fetch(`/env/config.json?t=${rand}`);
            const config = await response.text();
            this.parseJson(config, false);
        } catch (e) { }
    }
    async login(userId: string, password: string, captcha: string): Promise<UserProfile> {
        // let params = JSON.stringify({ userId, password, captcha });
        // let qs = "ask=@login&params=" + base16Encode(params);
        // let url = "/api/ask?" + qs;
        const params = { userId, password, captcha };
        const ask = "@login"
        let result = new UserProfile(this.appName);
        try {
            // let response = await fetch(url);
            // let json = await response.text();
            await result.fetchConfig();
            //console.log("fetchConfig:", JSON.stringify(this));
            const json = await fetchAskData(ask, params, false, result);
            if (json && result.parseJson(json, true))
                result.load();
            else
                result.msg = "登录失败，服务器拒绝处理登录数据";
            return result;
        } catch (error) {
            result.msg = "登录失败，无法连接服务器：" + error;
            result.logined = false;
            return result;
        }
    }
    logout(): UserProfile {
        let result = new UserProfile(this.appName)
        //result.save();
        return result;
    }
    asHtml(displayDefaultVoucherType: boolean = true): string {
        return `<p>登录码:${this.userId} 姓名:${this.userName} 类别:${this.userType}` +
            (displayDefaultVoucherType ? " 默认凭证类型:" + this.defaultVoucherType : "") + "</p>";
    }
}
